﻿// ------------------------------------------------------------------------
//    XBMControl - A compact remote controller for XBMC (.NET 3.5)
//    Copyright (C) 2008  Bram van Oploo (bramvano@gmail.com)
//                        Mike Thiels (Mike.Thiels@gmail.com)
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
// ------------------------------------------------------------------------

using System;
using System.Text;
using System.IO;
using System.Drawing;
using YATSE;

namespace XBMC
{
    public class XbmcVideo
    {
        readonly XbmcCommunicator _parent;

        public XbmcVideo(XbmcCommunicator p)
        {
            _parent = p;
        }

        public static string Hash(string input)
        {
            var chars = input.ToCharArray();
            for (var index = 0; index < chars.Length; index++)
            {
                if (chars[index] <= 127)
                    chars[index] = Char.ToLowerInvariant(chars[index]);
            }
            input = new string(chars);
            var mCrc = 0xffffffff;
            var bytes = Encoding.UTF8.GetBytes(input);
            foreach (var myByte in bytes)
            {
                mCrc ^= ((uint)(myByte) << 24);
                for (var i = 0; i < 8; i++)
                {
                    if ((Convert.ToUInt32(mCrc) & 0x80000000) == 0x80000000)
                    {
                        mCrc = (mCrc << 1) ^ 0x04C11DB7;
                    }
                    else
                    {
                        mCrc <<= 1;
                    }
                }
            }
            return String.Format("{0:x8}", mCrc);
        }

        public static bool ByteArrayToFile(string fileName, byte[] byteArray)
        {
            //try
            //{
                var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                fileStream.Write(byteArray, 0, byteArray.Length);
                fileStream.Close();
                return true;
            /*}
            catch (Exception exception)
            {
                Console.WriteLine("Exception caught in process: {0}", exception.ToString());
            }*/
            //return false;
        }


        public bool DownloadThumb(string hash,string destination)
        {
            var fileName = @"special://profile/Thumbnails/Video/" + hash[0] + "/" + hash + ".tbn";
            var fileExist = _parent.Request("FileExists", fileName);
            if (fileExist == null) return false;
            if (fileExist[0] == "True")
            {
               // try
              //  {
                    var downloadData = _parent.Download(fileName);
                    if (downloadData == null) return false;
                    //App.WriteToLog("DownloadData : " + downloadData);
                    var imageBytes = Convert.FromBase64String(downloadData);
                    return ByteArrayToFile(destination, imageBytes);
              //  }
               // catch (Exception) { }
            }
            App.WriteToLog("VideoThumb : " + hash + " - Does not exists");
            return false;
        }

        public bool DownloadMusicThumb(string hash, string destination)
        {
            if (hash == "NONE") return false;
            var fileName = @"special://profile/Thumbnails/Music/" + hash[0] + "/" + hash + ".tbn";
            var fileExist = _parent.Request("FileExists", fileName);
            if (fileExist == null) return false;
            if (fileExist[0] == "True")
            {
               // try
               // {
                    var downloadData = _parent.Download(fileName);
                    if (downloadData == null) return false;
                    //App.WriteToLog("DownloadData : " + downloadData);
                    var imageBytes = Convert.FromBase64String(downloadData);
                    return ByteArrayToFile(destination, imageBytes);
               // }
               // catch (Exception) {}
            }
            App.WriteToLog("MusicThumb : " + hash + " - Does not exists");
            return false;
        }


        public bool DownloadFanart(string hash,string destination)
        {
            var fileName = @"special://profile/Thumbnails/Video/Fanart/" + hash + ".tbn ";
            var fileExist = _parent.Request("FileExists", fileName);
            if (fileExist == null) return false;
            if (fileExist[0] == "True")
            {
              //  try
              // {
                    var downloadData = _parent.Download(fileName);
                    if (downloadData == null) return false;
                    var imageBytes = Convert.FromBase64String(downloadData);
                    return ByteArrayToFile(destination, imageBytes);
               // }
              //  catch (Exception) {}        
            }
            App.WriteToLog("VideoFanart : " + hash + " - Does not exists");
            return false;
        }



        public Image GetVideoThumb(string videoId)
        {
            Image thumbnail = null;
            //var client = new WebClient();
            var condition = (videoId == null) ? "" : " WHERE C09 LIKE '%%" + videoId + "%%'";
            var strPath = _parent.Request("QueryVideoDatabase", "SELECT strpath FROM movieview " + condition);
            var hashName = Hash(strPath[0] + "VIDEO_TS.IFO");

            var ipString = "P:\\Thumbnails\\Video\\" + hashName[0] + "\\" + hashName + ".tbn";

            var fileExist = _parent.Request("FileExists", ipString);

            if (fileExist[0] == "True")
            {
                try
                {
                    string[] downloadData = _parent.Request("FileDownload", ipString);

                    // Convert Base64 String to byte[]
                    var imageBytes = Convert.FromBase64String(downloadData[0]);
                    var ms = new MemoryStream(imageBytes, 0,
                      imageBytes.Length);

                    // Convert byte[] to Image
                    ms.Write(imageBytes, 0, imageBytes.Length);
                    thumbnail = Image.FromStream(ms, true);
                }
                catch (Exception)
                {
                    //thumbnail = Resources.video_32x32;
                }
            }
            //else
           // {
                //thumbnail = Resources.video_32x32;
            //}

            return thumbnail;
        }

        public string GetVideoPath(string movieName)
        {
            var condition = (movieName == null) ? "" : " WHERE C00 LIKE '%%" + movieName + "%%'";
            var tempStringList = _parent.Request("QueryVideoDatabase", "SELECT strpath FROM movieview " + condition);
            var tempString = tempStringList[0];
            tempString += "VIDEO_TS.IFO";
            return tempString;
        }

        public string[] GetVideoNames(string searchString)
        {
            var condition = (searchString == null) ? "" : " WHERE C00 LIKE '%%" + searchString + "%%'";
            return _parent.Request("QueryVideoDatabase", "SELECT C00 FROM movie " + condition);
        }

        public string[] GetVideoNames()
        {
            return GetVideoNames(null);
        }

        public string[] GetVideoYears(string searchString)
        {
            var condition = (searchString == null) ? "" : " WHERE C00 LIKE '%%" + searchString + "%%'";
            return _parent.Request("QueryVideoDatabase", "SELECT C07 FROM movie " + condition);
        }

        public string[] GetVideoYears()
        {
            return GetVideoYears(null);
        }

        public string[] GetVideoIMDB(string searchString)
        {
            var condition = (searchString == null) ? "" : " WHERE C00 LIKE '%%" + searchString + "%%'";
            return _parent.Request("QueryVideoDatabase", "SELECT C09 FROM movie " + condition);
        }

        public string[] GetVideoIMDB()
        {
            return GetVideoIMDB(null);
        }

        public string[] GetVideoIds(string searchString)
        {
            var condition = (searchString == null) ? "" : " WHERE C00 LIKE '%%" + searchString + "%%'";
            return _parent.Request("QueryVideoDatabase", "SELECT idMovie FROM movie" + condition + " ORDER BY idMovie");
        }

        public string[] GetVideoIds()
        {
            return GetVideoIds(null);
        }

        public string[] GetVideoLibraryInfo(string videoId)
        {
            var condition = (videoId == null) ? "" : " WHERE C09 LIKE '%%" + videoId + "%%'";
            return _parent.Request("QueryVideoDatabase", "SELECT * FROM movie " + condition);
        }

    }
}
